package com.etoak.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import com.etoak.common.core.constant.CommonConstant;
import com.etoak.common.core.vo.ResultVO;
import com.etoak.redis.service.RedisService;
import com.etoak.vo.CodeVo;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.apache.ibatis.javassist.bytecode.ByteArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/code")
public class CodeController {

    @Autowired
    private RedisService redisService;

    @Autowired
    private DefaultKaptcha kaptcha;

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @GetMapping("/getCode")
    public ResultVO<CodeVo> getCode() throws IOException {
        String text = kaptcha.createText();
        String[] textArray = text.split("@");

        String uuid = IdUtil.simpleUUID();
        String codeKey = CommonConstant.CODE_KEY_PREFIX + uuid;
        redisService.setex(codeKey,textArray[1],3, TimeUnit.MINUTES);

        /*
         * 将图片写入字节数组输出流, 图片转成二进制数组
         */
        BufferedImage bufferedImage = defaultKaptcha.createImage(textArray[0]);
        FastByteArrayOutputStream outputStream = new FastByteArrayOutputStream();
        ImageIO.write(bufferedImage, "png", outputStream);

        // 将图片的二进制数组转换成base64编码后的字符串
        String base64Encode = Base64.encode(outputStream.toByteArray());
        // 拼接后的codeUrl可以被img标签的src响应
        String codeUrl = "data:image/png;base64," + base64Encode;

        CodeVo codeVo = new CodeVo(uuid,codeUrl);
        return ResultVO.success(codeVo);
    }
}
